package com.kun.video.util;

import cn.hutool.core.util.StrUtil;
import javafx.scene.image.PixelFormat;
import javafx.scene.image.PixelReader;
import javafx.scene.image.WritableImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

/**
 * 图片工具类
 *
 * @author gzc
 * @since 2025/3/9
 **/
public class ImageUtil {
    private final static Logger log = LoggerFactory.getLogger(ImageUtil.class);

    public static BufferedImage savePng(WritableImage image, String outputFilePath) {
        BufferedImage bufferedImage = null;
        try {
            if (image == null || StrUtil.isBlank(outputFilePath)) {
                return bufferedImage;
            }
            int width = (int) image.getWidth();
            int height = (int) image.getHeight();
            // 创建BufferedImage
            bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
            // 获取像素数据
            PixelReader reader = image.getPixelReader();
            int[] pixels = new int[width * height];
            reader.getPixels(0, 0, width, height, PixelFormat.getIntArgbInstance(), pixels, 0, width);
            // 设置像素数据
            bufferedImage.setRGB(0, 0, width, height, pixels, 0, width);
            // 保存文件
            ImageIO.write(bufferedImage, "png", new File(outputFilePath));
            log.info("视频截图保存到【{}】成功！", outputFilePath);
        } catch (Exception e) {
            log.error("保存图片【{}】发生异常 -> {}", outputFilePath, e);
        }
        return bufferedImage;
    }
}
